package com.kelvem.saas.workbanch.core.manager.service;

import com.kelvem.saas.workbanch.core.base.BaseCriteria;
import com.kelvem.saas.workbanch.core.base.BaseService;
import com.kelvem.saas.workbanch.core.base.Page;
import com.kelvem.saas.workbanch.core.exception.SaasAssert;
import com.kelvem.saas.workbanch.core.exception.SaasException;
import com.kelvem.saas.workbanch.core.manager.dao.MetaTableActionDao;
import com.kelvem.saas.workbanch.core.manager.model.MetaTableActionEntity;
import com.kelvem.saas.workbanch.core.manager.request.MetaTableActionQueryVo;
import com.kelvem.saas.workbanch.core.utils.DateUtil;
import com.kelvem.saas.workbanch.fsm.dao.BaseDao;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 实体表行为Service
 *
 * @author kelvem
 * @version 1.0
 */
@Service
@Slf4j
public class MetaTableActionService extends BaseService<MetaTableActionEntity, MetaTableActionQueryVo> {

    @Resource
    private MetaTableActionDao metaTableActionDao;

    /**
     * 增加实体表行为
     *
     * @param metaTableAction 实体表行为信息
     * @return Long 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public Long addMetaTableAction(MetaTableActionEntity metaTableAction) {
        
        log.info("MetaTableActionService:addMetaTableAction:start, metaTableAction=【{}】", metaTableAction);
        SaasAssert.notNull(metaTableAction);
        
        try {
            if (metaTableAction.getCreateTime() == null) {
                metaTableAction.setCreateTime(DateUtil.now());
            }
            if (metaTableAction.getUpdateTime() == null) {
                metaTableAction.setUpdateTime(DateUtil.now());
            }
        
            metaTableActionDao.insert(metaTableAction);
            Long metaTableActionId = metaTableAction.getId();
            log.info("MetaTableActionService:addMetaTableAction:end, metaTableActionId={}", metaTableActionId);
        
            return metaTableAction.getId();
        } catch (Exception e) {
            String msg = String.format("MetaTableActionService:addMetaTableAction:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 修改实体表行为
     *
     * @param metaTableAction 实体表行为信息
     * @return 更新记录数
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateMetaTableAction(MetaTableActionEntity metaTableAction) {
        
        log.info("MetaTableActionService:updateMetaTableAction:start, metaTableAction=【{}】", metaTableAction);
        SaasAssert.notNull(metaTableAction);
        SaasAssert.notNull(metaTableAction.getId());

        try {
            int count = metaTableActionDao.updateById(metaTableAction);
            log.info("MetaTableActionService:updateMetaTableAction:end, count={}", count);
            return count;
        } catch (Exception e) {
            String msg = String.format("MetaTableActionService:updateMetaTableAction:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 删除实体表行为
     *
     * @param metaTableActionId 实体表行为id
     * @return 删除记录数
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteMetaTableAction(Long metaTableActionId) {

        log.info("MetaTableActionService:deleteMetaTableAction:start, metaTableActionId={}", metaTableActionId);
        SaasAssert.notNull(metaTableActionId);
        
        try {
            int count = metaTableActionDao.deleteById(metaTableActionId);
            log.info("MetaTableActionService:deleteMetaTableAction:end, count={}", count);
            return count;
        } catch (Exception e) {
            String msg = String.format("MetaTableActionService:deleteMetaTableAction:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }
    
    /**
     * 查询实体表行为分页数据
     *
     * @param metaTableActionQueryVo 查询用
     * @return Page<MetaTableActionDto>
     */
    public Page<MetaTableActionEntity> queryMetaTableActionPage(MetaTableActionQueryVo metaTableActionQueryVo) {
        
        log.info("MetaTableActionService:queryMetaTableActionPage:start, metaTableActionQueryVo=【{}】", metaTableActionQueryVo);
        SaasAssert.notNull(metaTableActionQueryVo);
        
        try {
            Page<MetaTableActionEntity> page = super.queryPage(metaTableActionQueryVo);
            log.info("MetaTableActionService:queryMetaTableActionPage:end, page.size={}", page.getRecords().size());
            return page;
        } catch (Exception e) {
            String msg = String.format("MetaTableActionService:queryMetaTableActionPage:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 查询实体表行为列表数据
     *
     * @param metaTableActionQueryVo 查询用
     * @return List<MetaTableAction>
     */
    public List<MetaTableActionEntity> queryMetaTableActionList(MetaTableActionQueryVo metaTableActionQueryVo) {
        
        log.info("MetaTableActionService:queryMetaTableActionList:start, metaTableActionQueryVo=【{}】", metaTableActionQueryVo);
        SaasAssert.notNull(metaTableActionQueryVo);
        
        try {
            List<MetaTableActionEntity> list = super.queryList(metaTableActionQueryVo);
            log.info("MetaTableActionService:queryMetaTableActionList:end, list.size={}", list.size());
            return list;
        } catch (Exception e) {
            String msg = String.format("MetaTableActionService:queryMetaTableActionList:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 根据id查询实体表行为信息
     *
     * @param metaTableActionId 实体表行为id
     * @return MetaTableAction
     */
    public MetaTableActionEntity getMetaTableActionById(Long metaTableActionId) {

        log.info("MetaTableActionService:getMetaTableActionById:start, metaTableActionId={}", metaTableActionId);
        SaasAssert.notNull(metaTableActionId);
        
        try {
            MetaTableActionEntity metaTableAction = metaTableActionDao.selectById(metaTableActionId);
            log.info("MetaTableActionService:getMetaTableActionById:end, metaTableActionInfo=【{}】", metaTableAction);
            return metaTableAction;
        } catch (Exception e) {
            String msg = String.format("MetaTableActionService:getMetaTableActionById:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 构建查询用Criteria
     * 基类的queryPage, queryList方法使用
     *
     * @param queryVo 查询用
     * @return BaseCriteria
     */
    @Override
    public BaseCriteria<MetaTableActionEntity> buildQueryCriteria(MetaTableActionQueryVo queryVo) {
        BaseCriteria<MetaTableActionEntity> criteria = new BaseCriteria<>();
        criteria.orderByDesc("meta_table_id");
        criteria.orderByAsc("sort_no");

        // 主键
        Long id = queryVo.getId();
        if (super.isNotEmpty(id)) {
            criteria.andEqualTo("id", queryVo.getId());
        }
        
        // 创建时间
        Date startCreateTime = queryVo.getStartCreateTime();
        if(super.isNotEmpty(startCreateTime)) {
            criteria.andGreaterThanOrEqualTo("createTime", startCreateTime);
        }
        Date endCreateTime = queryVo.getEndCreateTime();
        if(super.isNotEmpty(endCreateTime)) {
            criteria.andLessThanOrEqualTo("createTime", endCreateTime);
        }

        // 实体表id
        Long metaTableId = queryVo.getMetaTableId();
        if (super.isNotEmpty(metaTableId)) {
            criteria.andEqualTo("metaTableId", metaTableId);
        }

        // 关联id
        Long parentId = queryVo.getParentId();
        if (super.isNotEmpty(parentId)) {
            criteria.andEqualTo("parentId", parentId);
        }

        // 操作类型, page:跳页面; dialog:弹对话框; crud:增删改查; api:调接口; fsm:调状态机; redirect:跳url;sql:执行sql
        String operationType = queryVo.getOperationType();
        if (super.isNotEmpty(operationType)) {
            criteria.andEqualTo("operationType", operationType);
        }

        // 作用域类型, with_query:查询条件对象; with_id:id参数; with_table:表格行对象; with_info:表格行额外信息
        String scopeType = queryVo.getScopeType();
        if (super.isNotEmpty(scopeType)) {
            criteria.andEqualTo("scopeType", scopeType);
        }

        // 事件来源类型, system:系统; manual:人工
        String sourceType = queryVo.getSourceType();
        if (super.isNotEmpty(sourceType)) {
            criteria.andEqualTo("sourceType", sourceType);
        }

        // 创建人
        String createUid = queryVo.getCreateUid();
        if (super.isNotEmpty(createUid)) {
            criteria.andEqualTo("createUid", createUid);
        }

        // 更新人
        String updateUid = queryVo.getUpdateUid();
        if (super.isNotEmpty(updateUid)) {
            criteria.andEqualTo("updateUid", updateUid);
        }

        return criteria;
    }

    @Override
    public BaseDao<MetaTableActionEntity> getDao() {
        return this.metaTableActionDao;
    }

    /**
     * 查询实体行为表数据
     *
     * @param metaTableId 实体表id
     * @return List<MetaTableAction>
     */
    public List<MetaTableActionEntity> queryMetaTableActionList(Long metaTableId) {

        log.info("MetaTableActionService:queryMetaTableActionList:start, metaTableId=【{}】", metaTableId);
        SaasAssert.notNull(metaTableId);

        try {
            MetaTableActionQueryVo metaTableActionQueryVo = new MetaTableActionQueryVo();
            metaTableActionQueryVo.setMetaTableId(metaTableId);

            List<MetaTableActionEntity> list = super.queryList(metaTableActionQueryVo);
            log.info("MetaTableActionService:queryMetaTableActionList:end, list.size={}", list.size());
            return list;
        } catch (Exception e) {
            String msg = String.format("MetaTableActionService:queryMetaTableActionList:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 删除实体表事件
     *
     * @param metaTableId 实体表id
     * @return 删除记录数
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteByParentMetaTableId(Long metaTableId) {

        log.info("MetaTableActionService:deleteByParentMetaTableId:start, metaTableId={}", metaTableId);
        SaasAssert.notNull(metaTableId);

        try {
            int count = metaTableActionDao.deleteByParentMetaTableId(metaTableId);
            log.info("MetaTableActionService:deleteByParentMetaTableId:end, count={}", count);
            return count;
        } catch (Exception e) {
            String msg = String.format("MetaTableActionService:deleteByParentMetaTableId:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void copyMetaTableAction(List<MetaTableActionEntity> metaTableActionList, Long metaTableId) {

        for (MetaTableActionEntity metaTableAction:
                metaTableActionList) {
            metaTableAction.setId(null);
            metaTableAction.setCreateTime(DateUtil.now());
            metaTableAction.setUpdateTime(DateUtil.now());
            metaTableAction.setMetaTableId(metaTableId);
            this.addMetaTableAction(metaTableAction);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void importTableEvent(Long importTableId) {
        // todo 暂时importTableEvent使用999
        List<MetaTableActionEntity> defaultActionList = this.metaTableActionDao.queryMetaTableActionList(999L);

        this.copyMetaTableAction(defaultActionList, importTableId);
    }

}
